#include	"Balancer.h"
#include	<climits>

void Balancer::Add(uint64_t connect, int type, const std::string & ip, int port) {
	Del(connect);

	Device * device = new Device;
	device->type = type;
	device->connect = connect;
	device->ip = ip;
	device->port = port;
	device->capacity = 0;

	_devices[connect] = device;
}

void Balancer::Del(uint64_t connect) {
	auto it = _devices.find(connect);
	if (it != _devices.end()) {
		delete it->second;
		_devices.erase(it);
	}
}

void Balancer::Inc(uint64_t connect) {
	auto it = _devices.find(connect);
	if (it != _devices.end()) it->second->capacity++;
}

void Balancer::Dec(uint64_t connect) {
	auto it = _devices.find(connect);
	if (it != _devices.end()) it->second->capacity--;
}

Balancer::Device * Balancer::Peek(int type) {
	Device * find = nullptr;
	int capacity = INT_MAX;

	for (const auto & kv : _devices) {
		if (kv.second->type == type && capacity > kv.second->capacity) {
			find = kv.second;
			capacity = find->capacity;
		}
	}

	return find;
}

void Balancer::Foreach(int type, std::function<void(Device *)> processor) {
	for (auto & kv : _devices) {
		if (kv.second->type == type) processor(kv.second);
	}
}